package com.flappypig.thread;
import static java.lang.String.valueOf;

public class ThreadControl {
    public static void main(String[] args) throws InterruptedException {
        Thread[] threads = new Thread[100];
        for (int i = 99; i >= 0; i--) {
            threads[i] = new Thread(new ThreadTest(),valueOf(i));
        }
        for (int i = 0; i < 100; i++) {
            threads[i].start();
        }
    }
}
class ThreadTest implements Runnable {
    @Override
    public void run() {
        synchronized (Share.monitor) {
            while (Thread.currentThread().getName().equals(Share.flag.toString())) {
                try {
                    Share.monitor.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Share.flag);
            Share.incr();
            Share.monitor.notifyAll();
        }
    }
}

class Share {
    public static Object monitor = new Object();
    public static volatile Integer flag;
    static {
        flag = 0;
    }
    public static void incr() {
        flag++;
    }
}